package web

import (
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"net/http"
	"testPaper/common"
	"testPaper/model"
	"testPaper/response"
	"time"
)

// Login 管理员登录
func Login(c *gin.Context) {
	DB := common.GetDB()
	telephone := c.PostForm("telephone")
	password := c.PostForm("password")
	if len(password) < 6 {
		response.Reponse(c, http.StatusOK, 422, nil, "密码不能小于6位")
		return
	} else if len(telephone) != 11 {
		response.Reponse(c, http.StatusOK, 422, nil, "手机号输入不正确")
		return
	}
	var admin model.Admin
	DB.Where("telephone = ?", telephone).First(&admin)
	if admin.ID != 0 {
		err := bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(password))
		if err != nil {
			response.Reponse(c, http.StatusOK, 422, nil, "密码输入错误")
			return
		}
		//更新用户登录时间
		DB.First(&admin).Update("updated_at", time.Now())
		token, err := common.CreatWebToken(admin)
		if err != nil {
			response.Reponse(c, http.StatusOK, 500, nil, "token生成失败")
			return
		}
		response.Reponse(c, http.StatusOK, 200, gin.H{"token": token}, "登录成功")
		return

	} else {
		response.Reponse(c, http.StatusOK, 422, nil, "不存在该用户")
		return
	}
}
